package com.xiaoxie.common.utils;

import com.xiaoxie.common.union.R;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class HttpClientUtil {
    private final CloseableHttpClient httpClient;

    public HttpClientUtil(CloseableHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    /**
     * 发送get请求
     * @param url 请求url
     * @param params 请求参数
     * @param headers 请求头
     * @return 响应结果字符串
     * @throws IOException
     * @throws ParseException
     */
    public String sendGet(String url, Map<String,String> params, Map<String,String> headers) throws IOException, ParseException {
        String fullUrl = buildUrlWithParams(url, params);
        HttpGet httpGet = new HttpGet(fullUrl);

        if (headers != null) {
            // 便利headers，如果有传值则进行便利写到请求头当中
            headers.forEach(httpGet::setHeader);
        }
        return httpClient.execute(httpGet, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else {
                throw new RuntimeException("请求失败:" + statusCode);
            }
        });
    }

    /**
     * 发送get请求，并返回响应结果对象
     * @param url 请求url
     * @param params 请求参数
     * @param headers 请求头
     * @param location List<String>类型，每个元素指定从外到内定位到要转换为list列表的节点
     * @return R
     */
    public R sendGet(String url, Map<String,String> params, Map<String,String> headers, List<String> location) throws IOException, ParseException {
        String fullUrl = buildUrlWithParams(url, params);
        HttpGet httpGet = new HttpGet(fullUrl);

        if (headers != null) {
            // 便利headers，如果有传值则进行便利写到请求头当中
            headers.forEach(httpGet::setHeader);
        }
        return httpClient.execute(httpGet, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                List<Object> data = JSONUtils.getNodeAsList(responseBody, location);
                return R.ok(data);
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * 发送get请求，并返回响应结果对象
     * @param url 请求url
     * @param params 请求参数
     * @param headers 请求头参数
     * @param clazz 响应的json结果需要转换的对象类型
     * @return R
     * @throws IOException
     * @throws ParseException
     */
    public R sendGet(String url, Map<String,String> params, Map<String,String> headers, Class<?> clazz) throws IOException, ParseException {
        String fullUrl = buildUrlWithParams(url, params);
        HttpGet httpGet = new HttpGet(fullUrl);

        if (headers != null) {
            // 便利headers，如果有传值则进行便利写到请求头当中
            headers.forEach(httpGet::setHeader);
        }
        return httpClient.execute(httpGet, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.toBean(responseBody, clazz));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }


    /**
     * 发送post请求
     * @param url 请求url
     * @param params 请求参数
     * @param headers 请求头
     * @return 响应的字符串
     */
    public String sendPost(String url, Map<String,String> params, Map<String,String> headers) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        if(params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }

        if (headers != null) {
            // 便利headers，如果有传值则进行便利写到请求头当中
            headers.forEach(httpPost::setHeader);
        }

        return httpClient.execute(httpPost, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else {
                throw new RuntimeException("请求失败:" + statusCode);
            }
        });
    }

    /**
     *
     * @param url 请求url
     * @param params 请求参数
     * @param headers 请求头
     * @param clazz 响应结果对象
     * @return R
     */
    public R sendPost(String url, Map<String,String> params, Map<String,String> headers, Class<?> clazz) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        if(params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }

        if (headers != null) {
            // 便利headers，如果有传值则进行便利写到请求头当中
            headers.forEach(httpPost::setHeader);
        }

        return httpClient.execute(httpPost, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.toBean(responseBody, clazz));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    public R sendPost(String url, Map<String,String> params, Map<String,String> headers, List<String> location) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        if(params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }

        if (headers != null) {
            // 便利headers，如果有传值则进行便利写到请求头当中
            headers.forEach(httpPost::setHeader);
        }

        return httpClient.execute(httpPost, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                List<Object> data = JSONUtils.getNodeAsList(responseBody, location);
                return R.ok(data);
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * 发送put请求
     * @param url 请求url
     * @param body 请求体（json字符串）
     * @param headers 请求头
     * @return 响应的字符串
     * @Description: 这种方法式传入的是一个json字符串，springboot中使用@RequestBody接收
     */
    public String sendPut(String url, String body, Map<String,String> headers) throws IOException {
        HttpPut httpPut = new HttpPut(url);
        if (body != null) {
            httpPut.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        }
        if (headers != null) {
            headers.forEach(httpPut::setHeader);
        }
        return httpClient.execute(httpPut, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * 发送put请求
     * @param url 请求url
     * @param params 请求参数
     * @param headers 请求头
     * @return 响应字符串
     * @Description: 这种方法式传入的是一个map，springboot中使用@RequestParam接收
     */
    public String sendPut(String url, Map<String, String> params, Map<String,String> headers) throws IOException {
        HttpPut httpPut = new HttpPut(url);
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPut.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }
        if (headers != null) {
            headers.forEach(httpPut::setHeader);
        }
        return httpClient.execute(httpPut, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * put请求
     * @param url 请求url
     * @param params 请求参数
     * @param headers 响应头参数
     * @param clazz 响应结果对象
     * @return R
     * @Description: 这种方法式传入的是一个map，springboot中使用@RequestParam接收，响应的字符串会封装为指定的对象，返回再使用R封装后返回
     */
    public R sendPut(String url, Map<String, String> params, Map<String,String> headers, Class<?> clazz) throws IOException {
        HttpPut httpPut = new HttpPut(url);
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPut.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }
        if (headers != null) {
            headers.forEach(httpPut::setHeader);
        }

        return httpClient.execute(httpPut, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.toBean(responseBody, clazz));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }


    public R sendPut(String url, Map<String, String> params, Map<String,String> headers, List<String> location) throws IOException {
        HttpPut httpPut = new HttpPut(url);
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPut.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
        }
        if (headers != null) {
            headers.forEach(httpPut::setHeader);
        }

        return httpClient.execute(httpPut, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.getNodeAsList(responseBody, location));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * put请求
     * @param url 请求url
     * @param body 请求参数json字符串
     * @param headers 请求头参数
     * @param clazz 响应结果对象
     * @return R
     * @Description: 这种方法式传入的是一个json字符串，springboot中使用@RequestBody接收，响应的字符串会封装为指定的对象，返回再使用R封装后返回
     */
    public R sendPut(String url, String body, Map<String,String> headers, Class<?> clazz) throws IOException {
        HttpPut httpPut = new HttpPut(url);
        if (body != null) {
            httpPut.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        }
        if (headers != null) {
            headers.forEach(httpPut::setHeader);
        }
        return httpClient.execute(httpPut, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.toBean(responseBody, clazz));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    public R sendPut(String url, String body, Map<String,String> headers, List<String> location) throws IOException {
        HttpPut httpPut = new HttpPut(url);
        if (body != null) {
            httpPut.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        }
        if (headers != null) {
            headers.forEach(httpPut::setHeader);
        }
        return httpClient.execute(httpPut, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.getNodeAsList(responseBody, location));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * 发送delete请求
     * @param url 请求url
     * @param params 请求参数（作为查询参数）
     * @param headers 请求头参数
     * @return 响应的字符串
     */
    public String sendDelete(String url, Map<String,String> params, Map<String,String> headers) throws IOException {
        String fullUrl = buildUrlWithParams(url, params);
        HttpDelete httpDelete = new HttpDelete(fullUrl);
        if (headers != null) {
            headers.forEach(httpDelete::setHeader);
        }
        return httpClient.execute(httpDelete, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * delete请求
     * @param url 请求url
     * @param params 请求参数（作为查询参数）
     * @param headers 请求头参数
     * @param clazz 响应结果对象
     * @return R
     */
    public R sendDelete(String url, Map<String,String> params, Map<String,String> headers, Class<?> clazz) throws IOException {
        String fullUrl = buildUrlWithParams(url, params);
        HttpDelete httpDelete = new HttpDelete(fullUrl);
        if (headers != null) {
            headers.forEach(httpDelete::setHeader);
        }
        return httpClient.execute(httpDelete, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.toBean(responseBody, clazz));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    public R sendDelete(String url, Map<String,String> params, Map<String,String> headers, List<String> location) throws IOException {
        String fullUrl = buildUrlWithParams(url, params);
        HttpDelete httpDelete = new HttpDelete(fullUrl);
        if (headers != null) {
            headers.forEach(httpDelete::setHeader);
        }
        return httpClient.execute(httpDelete, response -> {
            int statusCode = response.getCode();
            if (statusCode == HttpStatus.SC_OK) {
                String responseBody = EntityUtils.toString(response.getEntity());
                return R.ok(JSONUtils.getNodeAsList(responseBody, location));
            } else {
                throw new RuntimeException("请求失败，返回状态码:" + statusCode);
            }
        });
    }

    /**
     * 构建带有查询参数的url
     * @param url 原始url
     * @param params 查询参数
     * @return 带有查询参数的url
     */
    private String buildUrlWithParams(String url, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return url;
        }
        StringBuilder urlBuilder = new StringBuilder(url);
        if (!url.contains("?")) {
            urlBuilder.append("?");
        } else {
            urlBuilder.append("&");
        }
        for (Map.Entry<String, String> entry : params.entrySet()) {
            urlBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))
                    .append("&");
        }
        // 移除最后一个&
        if (urlBuilder.charAt(urlBuilder.length() - 1) == '&') {
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        return urlBuilder.toString();
    }


}
